<template>
  <!-- <h1>添加一个新的SPU|修改已有的SPU结构</h1> -->
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请你输入SPU名称"
        v-model="SpuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId" style="width: 20vw">
        <el-option
          v-for="item in allTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请你输入描述"
        v-model="SpuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <!-- v-model:file-list 用于展示默认图片
                action:上传图片的接口地址
                on-preview:图片预览的回调
                on-remove:删除图片的回调
            -->
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handleUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性" inline>
      <!-- 展示销售属性的下拉菜单 -->
      <el-select
        v-model="saleAttrIdAndValueName"
        :placeholder="
          unSelectSaleAttr.length
            ? `剩${unSelectSaleAttr.length}个未选择`
            : '无'
        "
        style="width: 20vw"
      >
        <el-option
          :value="`${item.id}:${item.name}`"
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-button
        @click="addSaleAttr"
        :disabled="!saleAttrIdAndValueName"
        style="margin-left: 10px"
        type="primary"
        size="default"
        icon="Plus"
      >
        添加属性
      </el-button>
      <!-- table 展示销售属性与属性值的地方 -->
      <el-table border style="margin: 10px 0px" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #="{ row, $index }">
            <el-tag
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="row.id"
              closable
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              style="margin: 0px 10px"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              :ref="(vc: any) => (inputArr[$index] = vc)"
              @blur="toLook(row)"
              v-model="row.tempSaleAttrValue"
              v-if="row.flag == true"
              placeholder="请你输入属性值"
              size="small"
              style="width: 100px"
              clearable
            ></el-input>
            <el-button
              v-else
              @click="toEdit(row, $index)"
              type="primary"
              size="small"
              icon="Plus"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <!--          <template #="{ row, $index }">-->
          <template #="{}">
            <el-button type="danger" size="small" icon="Delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        :disabled="saleAttr.length > 0 ? false : true"
        type="primary"
        size="default"
        @click="save"
      >
        保存
      </el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {
  reqAddOrUpdateSpu,
  reqAllSaleAttr,
  reqAllTrademark,
  reqSpuHasSaleAttr,
  reqSpuImageList,
} from '@/api/product/spu'
import {
  AllTradeMark,
  HasSaleAttr,
  HasSaleAttrResponseData,
  SaleAttr,
  SaleAttrResponseData,
  SaleAttrValue,
  SpuData,
  SpuHasImage,
  SpuImage,
  TradeMark,
} from '@/api/product/spu/type'
import { ElMessage } from 'element-plus'
import { computed, nextTick, ref } from 'vue'

let $emit = defineEmits(['changeScene'])
// 点击取消按钮：通知父组件切换场景为1，展示已有的SPU的数据
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' }) // 取消留在当前页 update
}
// 存储数据
let allTradeMark = ref<TradeMark[]>([])
// 存储图片
let imgList = ref<SpuImage[]>([])
// 存储销售属性
let saleAttr = ref<SaleAttr[]>([])
// 全部的销售属性
let allSaleAttr = ref<HasSaleAttr[]>([])
// 存储已有的SPU对象，用于在模板中展示
let SpuParams = ref<SpuData>({
  // id?: number
  spuName: '',
  description: '',
  category3Id: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: [],
})

// 子组件被父组件调用的方法
const initHasSpuData = async (row: SpuData) => {
  SpuParams.value = row
  // row: 即为父组件传递过来的被点击的行的SPU对象
  // 获取全部品牌的数据
  let result: AllTradeMark = await reqAllTrademark()
  // 获取某一个品牌旗下全部售卖商品的图片
  let result1: SpuHasImage = await reqSpuImageList(row.id as number)
  // 获取已有的SPU的销售属性
  let result2: SaleAttrResponseData = await reqSpuHasSaleAttr(row.id as number)
  // 获取整个项目全部SPU的销售属性
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr()

  // 存储全部品牌数据
  allTradeMark.value = result.data
  // SPU对应的商品图片   使用map转成element需要的格式
  imgList.value = result1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  // SPU对应的销售属性
  saleAttr.value = result2.data
  // 获取整个项目全部SPU的销售属性
  allSaleAttr.value = result3.data
}

// 控制预览图片对话框显示隐藏
let dialogVisible = ref<boolean>(false)
// 存储预览图片地址
let dialogImageUrl = ref<string>('')
// 照片墙点击预览按钮的时候触发的钩子
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
// 照片墙删除图片的时候触发的钩子
// const handleRemove = (file: any, fileList: any) => {}
const handleRemove = () => {}
// 照片上传成功前的钩子，约束文件大小与类型
const handleUpload = (rowFile: any) => {
  if (
    rowFile.type == 'image/jpeg' ||
    rowFile.type == 'image/png' ||
    rowFile.type == 'image/gif'
  ) {
    if (rowFile.size / 1024 / 1024 < 3) {
      return true
    }
    ElMessage({ type: 'error', message: '上传图片大小不能超过 3MB!' })
    return false
  } else {
    ElMessage({
      type: 'error',
      message: '上传图片只能是 jpg/png/gif 格式!',
    })
    return false
  }
}
// 计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  let unSelectArr = allSaleAttr.value.filter((item) => {
    // every() 方法测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。
    return saleAttr.value.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectArr
})
// 将来收集还未选择的销售属性的ID与属性值的名字
let saleAttrIdAndValueName = ref<string>('')
//添加销售属性的方法
const addSaleAttr = () => {
  // es6解构
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  // 追加到数组当中
  saleAttr.value.push(newSaleAttr)
  // 清空收集的数据
  saleAttrIdAndValueName.value = ''
}

// 准备一个数组，将来存储对应的组件实例el-input
let inputArr = ref<any>([])

// 属性值添加按钮点击事件
const toEdit = (row: SaleAttr, $index: number) => {
  row.flag = true
  row.tempSaleAttrValue = ''
  nextTick(() => {
    inputArr.value[$index].focus()
    // console.log(inputArr.value[$index]);
  })
}
// 属性值添加失去焦点
const toLook = (row: SaleAttr) => {
  // 收集数据
  const { baseSaleAttrId, tempSaleAttrValue } = row
  //整理成服务器需要的格式
  let newSaleAttrValue: SaleAttrValue = {
    // baseSaleAttrId:baseSaleAttrId, //简写
    baseSaleAttrId,
    saleAttrValueName: tempSaleAttrValue as string,
  }
  // 非法判断
  if (tempSaleAttrValue!.trim().length == 0) {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    //切换为查看模式
    row.flag = false
    return
  }
  const repeat = row.spuSaleAttrValueList.find(
    (item) => item.saleAttrValueName == tempSaleAttrValue,
  )
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }

  // 追加到spuSaleAttrValueList中
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  //切换为查看模式
  row.flag = false
}
const save = async () => {
  // 整理参数
  // 1 照片墙
  /*
        [
            {
                "name": "background.jpg",
                "url": "blob:http://127.0.0.1:5173/527e30d2-ebb9-451c-8679-a46c51d50ddb",
                "uid": 1719998992398,
                "status": "success"
            },
            {
                "name": "螺丝整列机2.JPG",
                "percentage": 100,
                "status": "success",
                "size": 70493,
                "raw": {
                    "uid": 1719999009094
                },
                "uid": 1719999009094,
                "url": "blob:http://localhost:5173/71fbde1d-257b-41da-a048-907fe0848ce7",
                "response": {
                    "code": 200,
                    "message": "成功",
                    "data": "http://139.198.127.41:9000/sph/20240703/螺丝整列机2.JPG",
                    "ok": true
                }
            }
        ]
    */
  // element 上传照片插入imgList的内容，不符合定义的ts
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    // console.log((item.response && item.response.data)||item.url)
    return {
      imgName: item.name, //图片的名字
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  // 2 整理销售属性数据
  SpuParams.value.spuSaleAttrList = saleAttr.value
  // 新增或修改
  const result = await reqAddOrUpdateSpu(SpuParams.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    })
    //通知父组件切换场景
    $emit('changeScene', {
      flag: 0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    })
  }
}
// 添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
  // 清空上次输入的数据
  Object.assign(SpuParams.value, {
    spuName: '',
    description: '',
    category3Id: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
  })
  imgList.value = [] //清空图片
  saleAttr.value = [] // 清空销售属性
  saleAttrIdAndValueName.value = '' //清空销售属性下拉框

  // 存储三级分类id
  SpuParams.value.category3Id = c3Id
  // 获取全部品牌的数据
  let result: AllTradeMark = await reqAllTrademark()
  // 获取整个项目全部SPU的销售属性
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr()

  // 存储全部品牌数据
  allTradeMark.value = result.data
  // 获取整个项目全部SPU的销售属性
  allSaleAttr.value = result3.data
}
// 对外暴露
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style scoped></style>
